package com.cool.controller;

import com.cool.service.UserService;
import com.cool.util.JwtUtil;
import com.cool.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;
import java.util.HashMap;

@RestController
public class LoginController {
    @Autowired
    UserService userService;

    @PostMapping("/login")
    public Object login(@RequestBody UserVO userVO) {
        UserVO rUserVO = userService.getUserVO(userVO);
        if(rUserVO !=null ) {
            String jwt = JwtUtil.generateToken(userVO.getLogin_name());
            rUserVO.setLogin_time(new Timestamp(System.currentTimeMillis()));
            rUserVO.setToken(jwt);
            rUserVO.setCount(rUserVO.getCount()+1);
            if(rUserVO.getLogin_time()!=null){
                rUserVO.setLast_login_time(rUserVO.getLogin_time());
            }
            userService.updateUserVO(rUserVO);

            return new HashMap<String,Object>(){{
                put("token", jwt);
                put("user", rUserVO);
            }};
        }else {
            return new ResponseEntity(HttpStatus.UNAUTHORIZED);
        }
    }

    @GetMapping("get/user")
    public String  getUser(){
        System.out.println(1111111111);
        return "1111";
    }

}
